package com.fishery.customization.dao;

import com.fishery.customization.dao.reposity.BaseDao;
import com.fishery.customization.entity.ConstantValue;
import com.fishery.customization.entity.FixedLabel;
import com.fishery.customization.entity.OneLevelLabel;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import java.util.*;

@Repository
public class FixedLabelDao extends BaseDao<FixedLabel> {

	/**
	 * 查找出对应类型的标签并组装（带去重工作）
	 *
	 * @param types
	 * @return
	 */
	public List<OneLevelLabel> findFixedLabelsByTypes(List<String> types) {
		// 用于存储最终的一级标签
		Map<String, OneLevelLabel> map = new HashMap<>();
		// 查出所有固定规定类型对应的标签
		List<FixedLabel> fixedLabels = mongoOperations.find(Query.query(Criteria.where(getIdName()).in(types)),
				FixedLabel.class, getCollectionName());
		// 合并一级标签，需要做去重处理
		for (FixedLabel fixedLabel : fixedLabels) {
			for (OneLevelLabel label : fixedLabel.getLabels()) {
				if (map.containsKey(label.getName())) {
					List<String> mchildren = map.get(label.getName()).getChildren();
					label.getChildren().forEach(twoLevelName -> {
						if (!mchildren.contains(twoLevelName)) {
							mchildren.add(twoLevelName);
						}
					});
				} else {
					map.put(label.getName(), label);
				}
			}
		}
		return new ArrayList<>(map.values());
	}

	/**
	 * 查询出所有的基地类型
	 *
	 * @return
	 */
	public List<String> findAllTypesJsonOfBase() {
		Map<String, Object> fields = new HashMap<>();
		fields.put("_id", 1);
		fields.put("name", 1);
		return mongoOperations.find(getBasicQuery("_id", "", fields)
				.addCriteria(Criteria.where("_id")
						.nin(ConstantValue.LABEL_BASIC_TYPE)), String.class, getCollectionName());
	}
}
